<template>
  <div id="panel">
    <el-row :gutter="20">
      <!-- 左侧树结构（保持不变） -->
      <el-col :span="5" class="head-container">
        <el-radio-group
          v-model="sourceType"
          @change="handleSourceTypeChange"
          class="source-filter"
        >
          <el-radio-button label="wasteWater">废水</el-radio-button>
          <el-radio-button label="treatmentPlant">污水处理厂</el-radio-button>
        </el-radio-group>
        <tree-select v-model="deptName" @node-click="treeNodeClickk" />
      </el-col>

      <!-- 右侧内容区域（修改后） -->
      <el-col :span="19" class="body-container">
        <!-- 1. 右侧查询条件：改用 el-form 重构 -->
        <el-card class="queryForm">
          <el-form
            ref="queryForm"
            :model="queryForm"
            :inline="true"
            :label-position="'right'"
          >
            <el-form-item label="数据类型">
              <el-radio-group
                v-model="queryForm.dataTimeType"
                class="time-filter"
              >
                <el-radio-button label="realtime">实时数据</el-radio-button>
                <el-radio-button label="history">历史数据</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="关键字搜索">
              <el-input
                v-model="queryForm.searchKeyword"
                placeholder="输入关键字搜索"
                style="width: 200px; margin-right: 10px"
                @keyup.enter.native="handleSearch"
              ></el-input>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="handleSearch"
                >查询</el-button
              >
              <el-button
                type="primary"
                icon="el-icon-download"
                @click="handleExport"
                >导出</el-button
              >
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 数据展示区域（修复切换问题） -->
        <div class="data-content">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-radio-group
                v-model="queryForm.viewType"
                class="view-filter"
                @change="handleViewChange"
              >
                <el-radio label="table">表格</el-radio>
                <el-radio label="chart">图表</el-radio>
              </el-radio-group>
            </el-col>
          </el-row>
          <!-- 表格视图：确保 v-if 切换时重新渲染 -->
          <div
            v-if="queryForm.viewType === 'table'"
            class="table-container"
            key="table-view"
          >
            <el-table
              :data="tableData"
              border
              stripe
              style="width: 100%"
              v-loading="tableLoading"
            >
              <el-table-column
                prop="monitorTime"
                label="监测时间"
                width="180"
              ></el-table-column>
              <el-table-column prop="flow" label="流量(l/s)"></el-table-column>
              <el-table-column
                prop="flowEmission"
                label="流量排放量(m³)"
              ></el-table-column>
              <el-table-column prop="cod" label="COD(mg/l)"></el-table-column>
              <el-table-column
                prop="codEmission"
                label="COD排放量(kg)"
              ></el-table-column>
              <el-table-column prop="ph" label="pH值"></el-table-column>
              <el-table-column
                prop="ammoniaNitrogen"
                label="氨氮(mg/l)"
              ></el-table-column>
              <el-table-column
                prop="ammoniaNitrogenEmission"
                label="氨氮排放量(kg)"
              ></el-table-column>
              <el-table-column
                prop="totalNitrogen"
                label="总氮(mg/l)"
              ></el-table-column>
              <el-table-column
                prop="totalNitrogenEmission"
                label="总氮排放量(kg)"
              ></el-table-column>
              <el-table-column
                prop="totalPhosphorus"
                label="总磷(mg/l)"
              ></el-table-column>
              <el-table-column
                prop="totalPhosphorusEmission"
                label="总磷排放量(kg)"
              ></el-table-column>
            </el-table>

            <!-- 分页控件 -->
            <div class="pagination-container">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalCount"
              ></el-pagination>
            </div>
          </div>

          <!-- 图表视图：修复 DOM 渲染问题 -->
          <div
            v-else-if="queryForm.viewType === 'chart'"
            class="chart-container"
            key="chart-view"
          >
            <!-- 确保容器有明确高度，避免 echarts 初始化异常 -->
            <div
              ref="chartContainer"
              style="width: 100%; height: 100%; min-height: 400px"
            ></div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "onlinePollute",
  components: {
    TreeSelect: () => import("./TreeSelect.vue"),
  },
  data() {
    return {
      // 左侧树结构相关（保持不变）
      deptName: undefined,
      selTreeId: null,
      sourceType: "wasteWater", // 废水/污水处理厂筛选

      // 2. 重构：将查询相关字段整合为表单对象，便于管理
      queryForm: {
        viewType: "table", // 表格/图表视图切换（移到表单内统一管理）
        dataTimeType: "realtime", // 实时/历史数据切换
        searchKeyword: "", // 搜索关键词
      },

      // 表格数据（保持不变）
      tableData: [],
      tableLoading: false,
      currentPage: 1,
      pageSize: 10,
      totalCount: 0,

      // 图表实例（保持不变）
      chartInstance: null,
    };
  },
  methods: {
    // 树节点点击事件（保持不变）
    treeNodeClickk(val) {
      console.log(">>>选中的树节点ID", val);
      this.selTreeId = val;
      this.handleSearch();
    },

    // 污染源类型切换（保持不变）
    handleSourceTypeChange() {
      console.log(">>>污染源类型切换为:", this.sourceType);
      this.handleSearch();
    },

    // 视图切换处理（修复核心：增加图表销毁逻辑，避免DOM冲突）
    handleViewChange() {
      console.log(">>>视图切换为:", this.queryForm.viewType);

      // 切换视图前先销毁已有图表实例，防止DOM残留
      if (this.chartInstance) {
        this.chartInstance.dispose();
        this.chartInstance = null;
      }

      // 切换为图表视图时，确保DOM渲染完成后再初始化
      if (this.queryForm.viewType === "chart") {
        this.$nextTick(() => {
          // 双重保险：确保容器存在再初始化
          if (this.$refs.chartContainer) {
            this.initChart();
          }
        });
      }
    },

    // 查询数据（修改：使用 queryForm 表单数据）
    handleSearch() {
      if (!this.selTreeId) {
        this.$message.warning("请先选择左侧树节点");
        return;
      }

      this.tableLoading = true;

      // 模拟API请求（保持不变）
      setTimeout(() => {
        this.tableData = [
          {
            monitorTime: "2025-09-20 00:00:00",
            flow: 5.49,
            flowEmission: 19.77,
            cod: 50.6,
            codEmission: 1.0,
            ph: 7.85,
            ammoniaNitrogen: 12.91,
            ammoniaNitrogenEmission: 0.26,
            totalNitrogen: 15.2,
            totalNitrogenEmission: 0.3,
            totalPhosphorus: 0.85,
            totalPhosphorusEmission: 0.017,
          },
          {
            monitorTime: "2025-09-20 01:00:00",
            flow: 4.88,
            flowEmission: 17.56,
            cod: 50.6,
            codEmission: 0.89,
            ph: 7.92,
            ammoniaNitrogen: 12.91,
            ammoniaNitrogenEmission: 0.23,
            totalNitrogen: 14.8,
            totalNitrogenEmission: 0.26,
            totalPhosphorus: 0.82,
            totalPhosphorusEmission: 0.014,
          },
          {
            monitorTime: "2025-09-20 02:00:00",
            flow: 5.12,
            flowEmission: 18.44,
            cod: 49.8,
            codEmission: 0.92,
            ph: 7.78,
            ammoniaNitrogen: 12.75,
            ammoniaNitrogenEmission: 0.24,
            totalNitrogen: 15.1,
            totalNitrogenEmission: 0.28,
            totalPhosphorus: 0.87,
            totalPhosphorusEmission: 0.016,
          },
          {
            monitorTime: "2025-09-20 03:00:00",
            flow: 5.35,
            flowEmission: 19.26,
            cod: 51.2,
            codEmission: 0.98,
            ph: 7.81,
            ammoniaNitrogen: 13.05,
            ammoniaNitrogenEmission: 0.25,
            totalNitrogen: 15.5,
            totalNitrogenEmission: 0.3,
            totalPhosphorus: 0.89,
            totalPhosphorusEmission: 0.017,
          },
          {
            monitorTime: "2025-09-20 04:00:00",
            flow: 5.21,
            flowEmission: 18.76,
            cod: 50.3,
            codEmission: 0.94,
            ph: 7.76,
            ammoniaNitrogen: 12.88,
            ammoniaNitrogenEmission: 0.24,
            totalNitrogen: 15.3,
            totalNitrogenEmission: 0.29,
            totalPhosphorus: 0.86,
            totalPhosphorusEmission: 0.016,
          },
        ];

        this.totalCount = 50;
        this.tableLoading = false;

        // 修改：根据表单中的视图类型判断是否更新图表
        if (this.queryForm.viewType === "chart") {
          this.$nextTick(() => {
            if (this.$refs.chartContainer) {
              this.initChart();
            }
          });
        }
      }, 800);
    },

    // 导出数据（保持不变）
    handleExport() {
      if (!this.tableData.length) {
        this.$message.warning("没有可导出的数据");
        return;
      }
      this.$message.success("数据导出成功");
      // 实际项目中实现导出逻辑
    },

    // 初始化图表（优化：增加异常处理）
    initChart() {
      try {
        // 销毁已有实例（双重保险）
        if (this.chartInstance) {
          this.chartInstance.dispose();
        }

        // 创建新实例（增加DOM存在性判断）
        this.chartInstance = echarts.init(this.$refs.chartContainer);

        // 设置图表配置（保持不变）
        const option = {
          title: {
            text: `污染源监测数据趋势 - ${this.deptName || "未选择"}`,
            left: "center",
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow",
            },
          },
          legend: {
            data: ["流量(l/s)", "COD(mg/l)", "pH值", "氨氮(mg/l)"],
            top: 30,
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: this.tableData.map((item) => item.monitorTime),
          },
          yAxis: {
            type: "value",
            splitArea: {
              show: true,
            },
          },
          series: [
            {
              name: "流量(l/s)",
              type: "line",
              data: this.tableData.map((item) => item.flow),
              smooth: true,
              lineStyle: { width: 3 },
            },
            {
              name: "COD(mg/l)",
              type: "line",
              data: this.tableData.map((item) => item.cod),
              smooth: true,
              lineStyle: { width: 3 },
            },
            {
              name: "pH值",
              type: "line",
              data: this.tableData.map((item) => item.ph),
              smooth: true,
              lineStyle: { width: 3 },
            },
            {
              name: "氨氮(mg/l)",
              type: "line",
              data: this.tableData.map((item) => item.ammoniaNitrogen),
              smooth: true,
              lineStyle: { width: 3 },
            },
          ],
        };

        this.chartInstance.setOption(option);
      } catch (error) {
        console.error("图表初始化失败:", error);
        this.$message.error("图表加载失败，请重试");
      }
    },

    // 分页相关方法（保持不变）
    handleSizeChange(val) {
      this.pageSize = val;
      this.handleSearch();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handleSearch();
    },

    // 窗口大小变化时重绘图表（优化：增加存在性判断）
    handleResize() {
      if (this.chartInstance && this.queryForm.viewType === "chart") {
        this.chartInstance.resize();
      }
    },
  },
  watch: {
    // 修改：监听表单中的视图类型和表格数据变化
    "queryForm.viewType": function (newVal) {
      // 当视图切换为图表且表格有数据时，重新初始化图表
      if (newVal === "chart" && this.tableData.length > 0) {
        this.$nextTick(() => {
          if (this.$refs.chartContainer) {
            this.initChart();
          }
        });
      }
    },
    // 监听表格数据变化，更新图表（修改：使用表单视图类型）
    tableData() {
      if (this.queryForm.viewType === "chart" && this.chartInstance) {
        this.initChart();
      }
    },
  },
  mounted() {
    // 监听窗口大小变化（保持不变）
    window.addEventListener("resize", this.handleResize);
  },
  beforeDestroy() {
    // 移除事件监听（保持不变）
    window.removeEventListener("resize", this.handleResize);

    // 销毁图表实例（保持不变）
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  },
};
</script>

<style lang="scss" scoped>
#panel {
  padding: 15px;
  min-height: calc(100% - 20px);
  margin: 0;
  background-color: #f5f7fa;
}

.head-container {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: calc(100vh - 50px);
  display: flex;
  flex-direction: column;
}

.body-container {
  height: calc(100vh - 50px);
  display: flex;
  flex-direction: column;
}

// 左侧污染源类型筛选
.source-filter {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

// 右侧筛选区域
.right-filters {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  flex-wrap: wrap;
  gap: 15px;
}

.time-filter {
  display: flex;
  gap: 10px;
}

.search-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.view-filter {
  display: flex;
  gap: 10px;
}

// 数据内容区域
.data-content {
  flex: 1;
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

// 表格容器
.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.el-table {
  flex: 1;
  overflow-y: auto;
}

// 分页容器
.pagination-container {
  margin-top: 15px;
  text-align: right;
}

// 图表容器
.chart-container {
  flex: 1;
  min-height: 400px;
}

// 响应式调整
@media (max-width: 1200px) {
  .right-filters {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
